import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 辅助函数：判断日期是否在本周
function isThisWeek(dateStr) {
  const date = new Date(dateStr);
  const today = new Date();
  const firstDayOfWeek = new Date(today.setDate(today.getDate() - today.getDay()));
  const lastDayOfWeek = new Date(today.setDate(today.getDate() + 6));
  return date >= firstDayOfWeek && date <= lastDayOfWeek;
}

export const useHealthStore = defineStore('health', () => {
  // 状态数据，从 localStorage 读取，若不存在则用默认值
  const exercises = ref(JSON.parse(localStorage.getItem('exercises')) || [
    { type: '跑步', duration: 30, date: '2023-11-15' },
    { type: '游泳', duration: 45, date: '2023-11-16' }
  ]);

  const diets = ref(JSON.parse(localStorage.getItem('diets')) || [
    { food: '鸡胸肉', calories: 165, date: '2023-11-15' },
    { food: '沙拉', calories: 120, date: '2023-11-16' }
  ]);

  const sleeps = ref(JSON.parse(localStorage.getItem('sleeps')) || [
    { duration: 7, quality: '良好', date: '2023-11-15' },
    { duration: 6.5, quality: '一般', date: '2023-11-16' }
  ]);

  const goals = ref(JSON.parse(localStorage.getItem('goals')) || {
    exercise: 150,  // 每周150分钟运动目标
    calories: 2000, // 每日2000大卡
    sleep: 7        // 每日7小时睡眠
  }); // 修正：补充闭合括号

  // 计算属性
  const todayExercise = computed(() => {
  try {
    const today = new Date().toISOString().split('T')[0]
    return exercises.value
      .filter(e => e.date === today)
      .reduce((sum, e) => sum + (Number(e.duration) || 0), 0)
  } catch (e) {
    console.error("今日运动计算错误:", e)
    return 0
  }
})

  const todayCalories = computed(() => {
    const today = new Date().toISOString().split('T')[0];
    return diets.value
      .filter(d => d.date === today)
      .reduce((sum, d) => sum + d.calories, 0);
  });

  const todaySleep = computed(() => {
    const today = new Date().toISOString().split('T')[0];
    const sleep = sleeps.value.find(s => s.date === today);
    return sleep ? sleep.duration : 0;
  });

  const weeklyExercise = computed(() => {
    return exercises.value
      .filter(e => isThisWeek(e.date))
      .reduce((sum, e) => sum + e.duration, 0);
  });

  const exerciseProgress = computed(() => {
    return Math.min((weeklyExercise.value / goals.value.exercise) * 100, 100);
  });

  const calorieProgress = computed(() => {
    return Math.min((todayCalories.value / goals.value.calories) * 100, 100);
  });

  const sleepProgress = computed(() => {
    return Math.min((todaySleep.value / goals.value.sleep) * 100, 100);
  });

  // 操作方法：更新数据到 localStorage
  function addExercise(record) {
    exercises.value.push(record);
    localStorage.setItem('exercises', JSON.stringify(exercises.value));
  }

  function addDiet(record) {
    diets.value.push(record);
    localStorage.setItem('diets', JSON.stringify(diets.value));
  }

  function addSleep(record) {
    sleeps.value.push(record);
    localStorage.setItem('sleeps', JSON.stringify(sleeps.value));
  }

  function setGoals(newGoals) {
    goals.value = newGoals;
    localStorage.setItem('goals', JSON.stringify(goals.value));
  }

  // 获取最近7天的数据，用于图表展示
  function getWeeklyData() {
    const labels = Array(7).fill().map((_, i) => {
      const d = new Date();
      d.setDate(d.getDate() - i);
      return d.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
    }).reverse();

    const exerciseData = Array(7).fill(0);
    const calorieData = Array(7).fill(0);
    const sleepData = Array(7).fill(0);

    const today = new Date();
    today.setHours(0, 0, 0, 0);

    for (let i = 0; i < 7; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() - (6 - i));
      const dateStr = date.toISOString().split('T')[0];

      // 计算运动数据
      exerciseData[i] = exercises.value
        .filter(e => e.date === dateStr)
        .reduce((sum, e) => sum + e.duration, 0);

      // 计算饮食数据
      calorieData[i] = diets.value
        .filter(d => d.date === dateStr)
        .reduce((sum, d) => sum + d.calories, 0);

      // 计算睡眠数据
      const sleep = sleeps.value.find(s => s.date === dateStr);
      sleepData[i] = sleep ? sleep.duration : 0;
    }

    return { labels, exerciseData, calorieData, sleepData };
  }

  return {
    exercises, diets, sleeps, goals,
    todayExercise, todayCalories, todaySleep,
    exerciseProgress, calorieProgress, sleepProgress,
    addExercise, addDiet, addSleep, setGoals,
    getWeeklyData
  };
});